#include "screenmanager.h"
#include <QApplication>
#include <QScreen>
#include <QDesktopWidget>
#include <QDebug>
#include <QPlatformScreen>
#include <QWidget>
#include <algorithm>

ScreenManager::ScreenManager(QObject *parent)
    : QObject(parent)
{
    initializeScreens();
    
    // 连接屏幕变化信号
    connect(qApp, &QApplication::screenAdded, this, &ScreenManager::initializeScreens);
    connect(qApp, &QApplication::screenRemoved, this, &ScreenManager::initializeScreens);
}

void ScreenManager::initializeScreens()
{
    screens = qApp->screens();
    qDebug() << "检测到" << screens.size() << "个屏幕";
    
    for (int i = 0; i < screens.size(); ++i) {
        QScreen *screen = screens[i];
        qDebug() << "屏幕" << i << ":" << screen->name() 
                 << "几何:" << screen->geometry()
                 << "可用几何:" << screen->availableGeometry()
                 << "逻辑DPI:" << screen->logicalDotsPerInch();
    }
}

QRect ScreenManager::getPrimaryScreenAvailableGeometry() const
{
    QScreen *primaryScreen = qApp->primaryScreen();
    if (primaryScreen) {
        return primaryScreen->availableGeometry();
    }
    
    // 如果无法获取主屏幕，返回默认值
    return QRect(0, 0, 1920, 1080);
}

QList<QScreen*> ScreenManager::getAllScreens() const
{
    return screens;
}

QList<QRect> ScreenManager::getAllScreensAvailableGeometry() const
{
    QList<QRect> geometries;
    for (QScreen *screen : screens) {
        geometries.append(screen->availableGeometry());
    }
    return geometries;
}

QRect ScreenManager::getScreenAvailableGeometry(QScreen *screen) const
{
    if (screen) {
        return screen->availableGeometry();
    }
    return QRect();
}

int ScreenManager::getScreenCount() const
{
    return screens.size();
}

QRect ScreenManager::getVirtualGeometry() const
{
    return qApp->primaryScreen()->virtualGeometry();
}

QList<QRect> ScreenManager::getMultiScreenAvailableGeometry() const
{
    QList<QRect> availableGeometries;
    for (QScreen *screen : screens) {
        availableGeometries.append(screen->availableGeometry());
    }
    return availableGeometries;
}

QRect ScreenManager::getOptimalMultiScreenLayout() const
{
    if (screens.isEmpty()) {
        return QRect(0, 0, 1920, 1080);
    }
    
    if (screens.size() == 1) {
        return screens.first()->availableGeometry();
    }
    
    // 计算包含所有屏幕可用区域的最小矩形
    QRect boundingRect = screens.first()->availableGeometry();
    for (int i = 1; i < screens.size(); ++i) {
        boundingRect = boundingRect.united(screens[i]->availableGeometry());
    }
    
    return boundingRect;
}